package com.wmeimob.fastboot.jiubei.controller;

import com.github.pagehelper.PageInfo;
import com.wmeimob.fastboot.core.context.PageContext;
import com.wmeimob.fastboot.core.exception.CustomException;
import com.wmeimob.fastboot.jiubei.entity.Member;
import com.wmeimob.fastboot.jiubei.service.MemberService;
import com.wmeimob.fastboot.starter.security.context.SecurityContext;
import com.wmeimob.fastboot.util.StringUtils;
import com.wmeimob.fastboot.jiubei.entity.UserAddress;
import com.wmeimob.fastboot.jiubei.result.RestResponse;
import com.wmeimob.fastboot.jiubei.result.RestResults;
import com.wmeimob.fastboot.jiubei.service.UserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author wjt
 * @version 1.0
 * @className UserAddressController
 * @description 【】控制器
 * @date Tue Aug 18 16:45:30 CST 2020
 **/
@RestController
@RequestMapping("userAddress")
@Slf4j
public class UserAddressController {

    @Resource
    private UserAddressService userAddressService;
    @Resource
    private MemberService memberService;
    /**
     * 分页查询
     *
     * @param userAddress
     * @return
     */
    @GetMapping
    public RestResults queryForUserAddress(UserAddress userAddress) {
        Member member = SecurityContext.getUser();
        userAddress.setUserId(member.getId());
        PageContext.startPage();
        return RestResponse.makeOKRsp(new PageInfo<UserAddress>(userAddressService.list(userAddress)));
    }


    /**
     * 查询-<通过id查询>
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public RestResults queryForUserAddressById(@PathVariable("id") Object id) {
        return RestResponse.makeOKRsp(userAddressService.queryUserAddressById(id));
    }


    /**
     * 添加
     *
     * @param userAddress
     * @return
     */
    @PostMapping("/add")
    public RestResults insertForUserAddress(@RequestBody UserAddress userAddress) {
        if (StringUtils.isEmpty(userAddress.getAddress())) {
            throw new CustomException("地址为空");
        }
        Member member = SecurityContext.getUser();
        userAddress.setUserId(member.getId());
        userAddressService.addUserAddress(userAddress);
        return RestResponse.makeOKRsp();
    }



    /**
     * 修改
     *
     * @param userAddress
     * @return
     */
    @PutMapping("/update")
    public RestResults updateForUserAddress(@RequestBody UserAddress userAddress) {
        if (StringUtils.isEmpty(userAddress.getAddress())) {
            throw new CustomException("地址为空");
        }
        userAddressService.modifyUserAddress(userAddress);
        return RestResponse.makeOKRsp();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public RestResults removeForUserAddress(@PathVariable("id") Object id) {
        userAddressService.removeUserAddress(id);
        return RestResponse.makeOKRsp();
    }
}
